TaoHopDongPanel = Ext.extend(AbstractPanel, {
    layout: 'anchor',
    defaults: {anchor: '100%'},
    
    exportUrl : 'hopDong/export',
    
	initKhachHangFieldSet : function() {
		var fieldPlugin = new CustomizedFieldPlugin();
		this.hoTenTextField = new Ext.form.TextField({
			name : "hoTen",
			width : 250,
			fieldLabel : lang.text.kh.hoTen,
			autoCreate: {
	            tag: 'input', type: 'text', size: '20',
	            autocomplete: 'off', maxlength: '50'},
			allowBlank : false,
			mandatory : true,
			plugins : fieldPlugin,
			value : 'p'
		});
		
		this.diaChiTextField = new Ext.form.TextField({
			name : "diaChi",
			width : 250,
			fieldLabel : lang.text.kh.dchi,
			autoCreate: {
	            tag: 'input', type: 'text', size: '20',
	            autocomplete: 'off', maxlength: '100'},
			allowBlank : false,
			mandatory : true,
			plugins : fieldPlugin,
			value : 'p'
		});
		
		this.dienThoaiTextField = new Ext.form.TextField({
			name : "dienThoai",
			width : 250,
			fieldLabel : lang.text.kh.phone,
			autoCreate: {
	            tag: 'input', type: 'text', size: '20',
	            autocomplete: 'off', maxlength: '30'}
		});
		
		var leftCtn = new Ext.Container({
			layout : 'customizedlayout',
			labelWidth : 120,
			columnWidth: .5,
			items : [this.hoTenTextField, this.diaChiTextField, this.dienThoaiTextField]
		});
		
		this.tinhThanhCombo = new Ext.form.ComboBox({
			name : 'tinhThanh',
            fieldLabel : lang.text.kh.tinhThanh,
            width : 250,
            forceSelection : true,
            expandOnFocus : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
                fields : ['maDuLieu', 'giaTri']
            }),
			allowBlank : false,
			mandatory : true,
			plugins : fieldPlugin
		});
		
		this.quanHuyenCombo = new Ext.form.ComboBox({
			name : 'quanHuyen',
            fieldLabel : lang.text.kh.quanHuyen,
            width : 250,
            expandOnFocus : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
            	url : 'hopDong/reloadQuanHuyenByThanhPho',
            	autoLoad : false,
                fields : ['maDuLieu', 'giaTri']
            }),
			allowBlank : false,
			mandatory : true,
			plugins : fieldPlugin
		});
		
		this.phuongXaCombo = new Ext.form.ComboBox({
			name : 'phuongXa',
            fieldLabel : lang.text.kh.phuongXa,
            width : 250,
            expandOnFocus : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
            	url : 'hopDong/reloadPhuongXaByQuanHuyen',
            	autoLoad : false,
                fields : ['maDuLieu', 'giaTri']
            }),
			allowBlank : false,
			mandatory : true,
			plugins : fieldPlugin
		});
		
		var rightCtn = new Ext.Container({
			layout : 'customizedlayout',
			labelWidth : 120,
			columnWidth: .5,
			items : [this.tinhThanhCombo, this.quanHuyenCombo, this.phuongXaCombo]
		});
		
		return new Ext.form.FieldSet({
			title : lang.text.kh.khInfo,
			autoHeight : true,
			height : 150,
			layout : 'column',
			items : [leftCtn, {xtype : 'spacer', width : 20}, rightCtn]
		});
	},
	
	initButtonBar : function() {
		if (this.isEdit) {
			this.luuBtn = new Ext.Button({
				width : 130,
				text : this.isEdit ? lang.text.luu : lang.text.luuTaoMoi
			});
			
			this.inBtn = this.createInPhieuThuBtn(false);
			
			this.traHangBtn = new Ext.Button({
				width : 80,
				text : lang.text.pt.traHang
			});
			
			this.denHangBtn = new Ext.Button({
				width : 80,
				text : lang.text.pt.denHang
			});
			
			this.thoatBtn = new Ext.Button({
				width : 40,
				text : lang.text.thoat
			});
			
			return new Ext.Container({
				layout : 'hbox',
				items : [this.luuBtn, {xtype : 'spacer', width : 13},
				         this.inBtn, {xtype : 'spacer', width : 13},
				         this.traHangBtn, {xtype : 'spacer', width : 13}, 
				         this.denHangBtn, {xtype : 'spacer', width : 13}, 
				         this.thoatBtn]
			});
		} else {
			this.luuBtn = new Ext.Button({
				width : 130,
				text : lang.text.luuTaoMoi
			});
			
			this.luuInBtn = this.createInPhieuThuBtn(true);
			
			this.thoatBtn = new Ext.Button({
				width : 40,
				text : lang.text.thoat
			});
			
			return new Ext.Container({
				layout : 'hbox',
				items : [this.luuBtn, {xtype : 'spacer', width : 13}, this.luuInBtn, {xtype : 'spacer', width : 13}, this.thoatBtn]
			});
		}
	},
	
	createInPhieuThuBtn : function(haveOnlyMaVachMenu){
		var menu = [{text    : lang.text.inFullPhieuThu, handler : this.saveAndInPhieu, scope : this},
			        {text    : lang.text.inKhachHang, handler : this.saveAndInKhachHang, scope : this},
			        {text    : lang.text.inMaVach, handler : this.saveAndInMaVach, scope : this}];
		if(!haveOnlyMaVachMenu){
			menu = [{text    : lang.text.inFullPhieuThu, handler : this.saveAndInPhieu, scope : this},
			        {text    : lang.text.inKhachHang, handler : this.saveAndInKhachHang, scope : this}];
		}
		
		
		return new Ext.SplitButton({
			width : 130,
			text : lang.text.luuIn,
			isClickOnArrow : function(e){
				// Show menu by default when click on button.
				return true;
			},
			menu : menu
		});
	},
    
	initComponent : function() {
		this.isEdit = ApplicationManager.isEditHd;
		this.hdFieldSet = new HopDongInfoFieldSet({
			isEdit : this.isEdit
		});
		this.khFieldSet = this.initKhachHangFieldSet();
		this.buttonBar = this.initButtonBar();
		
		this.formLabel = new Ext.form.Label({
			cls : 'main-title',
			text : this.isEdit ? lang.text.menu.suaHd.toUpperCase() : lang.text.menu.taoHd.toUpperCase()
		});
		
		this.formLabelContainer = new Ext.Container({
			cls : 'field-align-center',
			items : [this.formLabel]
		});
		
		this.items = [this.formLabelContainer,
				      this.hdFieldSet, {xtype : 'spacer', height : 10}, 
					  this.khFieldSet, {xtype : 'spacer', height : 10}, this.buttonBar];
		TaoHopDongPanel.superclass.initComponent.call(this);
	},
	
	afterRender : function() {
		this.submitButtons = [this.luuBtn, this.luuInBtn];
		this.on('afterrender', this.initData, this);
		this.tinhThanhCombo.on('select', this.reloadQuanHuyenByThanhPho, this);
		this.quanHuyenCombo.on('select', this.reloadPhuongXaByQuanHuyen, this);
		this.hoTenTextField.on('blur', function(f) {
			var value = f.getValue();
			if (value != null && value != "") {
				f.setValue(value);
			}
		}, this);
		this.diaChiTextField.on('blur', function(f) {
			var value = f.getValue();
			if (value != null && value != "") {
				f.setValue(value);
			}
		}, this);
		if (this.isEdit) {
			this.justUseDefaultHotKeys = false;
			if (ApplicationManager.callbackMsg) {
	    		this.formMessage.showMessages(
	                    [FormMessageType.INFO], [ApplicationManager.callbackMsg.msg]);
	    		this.formMessage.setVisible(true);
			}
			this.disableComponents();
			this.hdFieldSet.thuNganCombo.clearValue();
			this.hdFieldSet.ngayBanDateField.setValue(null);
			this.traHangBtn.on('click', this.openSuaHdTraHang, this);
	    	this.denHangBtn.on('click', this.openSuaHdDenHang, this);
		} 
		TaoHopDongPanel.superclass.afterRender.call(this);		
	},
	
	initHotKey : function() {
    	var defaultHotKeys = this.defaultHotKeys();
    	this.keys = new Ext.KeyMap(this.el, [defaultHotKeys[0], defaultHotKeys[1], {
	        key: 't',
	        ctrl : true,
	        alt : true,
	        fn: this.openSuaHdTraHang,
	        scope: this
	    }, {
	        key: 'd',
	        ctrl : true,
	        alt : true,
	        fn: this.openSuaHdDenHang,
	        scope: this
	    }, {
	        key: 'i',
	        ctrl : true,
	        alt : true,
	        fn: this.inPhieuThu,
	        scope: this
	    }]);
    },
	
	initData : function() {
		Ext.Ajax.request({
            url : 'hopDong/initData',
            method : 'GET',
            scope : this,
            success : function(response, opts){
                var result = Ext.decode(response.responseText); 
                this.hdFieldSet.doiTruongCombo.store.loadData(result.doiTruong);
                DisplayType = Ext.data.Record.create([
                                                      {name: "id", type: "number"},
                                                      {name: "maNv", type: "string"}
                                                  ]);
                this.hdFieldSet.doiTruongCombo.store.insert(0, new DisplayType({
                	id : null,
                	maNv : " "
                }));
                this.hdFieldSet.nvBan1Combo.store.loadData(result.nvBan);
                this.hdFieldSet.nvBan2Combo.store.loadData(result.nvBan);
                this.hdFieldSet.thuNganCombo.store.loadData(result.thuNgan);
                this.hdFieldSet.thuNganCombo.store.insert(0, new DisplayType({
                	id : null,
                	maNv : lang.text.cty
                }));
                if (!this.isEdit) {
                	this.hdFieldSet.thuNganCombo.setValue(null);	
				}
                this.tinhThanhCombo.store.loadData(result.tinhThanh);
            }, 
            failure : function() {
            }
        });
	},
	
	reloadQuanHuyenByThanhPho : function(combo, record, idx) {
		this.quanHuyenCombo.clearValue();
		this.phuongXaCombo.clearValue();
		this.phuongXaCombo.store.removeAll();
		this.quanHuyenCombo.store.setBaseParam('maTinh', record.get('maDuLieu'));
		this.quanHuyenCombo.store.load();
	},
	
	reloadPhuongXaByQuanHuyen : function(combo, record, idx) {
		this.phuongXaCombo.clearValue();
		this.phuongXaCombo.store.setBaseParam('maQuanHuyen', record.get('maDuLieu'));
		this.phuongXaCombo.store.load();
	},
	
	saveAndInPhieu : function(){
		this.exportUrl = 'hopDong/export';
		this.doSaveHopDong(this.isEdit ? 'hopDong/edit' : 'hopDong/save', true);
	},
	
	saveAndInMaVach : function(){
		this.exportUrl = 'inMaVach/export';
		this.doSaveHopDong(this.isEdit ? 'inMaVach/edit' : 'inMaVach/save', true);
	},
	
	saveAndInKhachHang : function(){
		this.exportUrl = 'inKhachHang/export';
		this.doSaveHopDong(this.isEdit ? 'inKhachHang/edit' : 'inKhachHang/save', true);
	},
	
	doSaveHopDong : function(url, inPhieuThu){
		var giaTriHd = this.hdFieldSet.giaTriTextField.getValue();
		var tienTraTruoc = this.hdFieldSet.tienTraTruocTextField.getValue();
		var tienDaThu = this.hdFieldSet.tienDaThuTextField.getValue();
		var tienConLai = Utility.getRawValueOfNumericField(this.hdFieldSet.tienConLaiTextField);
		if (giaTriHd == 0 || giaTriHd == null || giaTriHd == "" || (tienDaThu + tienConLai + tienTraTruoc != giaTriHd && !this.hdFieldSet.thuTienNgayChkbox.checked)) {
			Ext.Msg.alert(lang.text.ktraDlieu, lang.msg.inconsistentData);
			return;
		}
		
		if ((this.hdFieldSet.doiTruongCombo.getValue() == "" || this.hdFieldSet.doiTruongCombo.getValue() == null) 
				&& this.hdFieldSet.nvBan1Combo.getValue() != this.hdFieldSet.nvBan2Combo.getValue()) {
			Ext.Msg.alert(lang.text.ktraDlieu, lang.msg.inconsistentNvBan);
			return;
		}
		
		this.disableButtons();
		this.getForm().submit({
		    url : url,
            waitMsg: lang.text.saving,
            params : {
            	tienConLai : tienConLai
            },
            waitMsgTarget : true,
            success : function(action, response) {
            	this.enableButtons();
            	var result = Ext.decode(response.response.responseText);
            	if (result.success) {
            		if(inPhieuThu){
        				this.exportPhieuThu(result.id);
        			}
            		if (!this.isEdit) {
            			this.hdFieldSet.thuTienNgayChkbox.setValue(false);
                    	this.hoTenTextField.clearInvalid();
						this.hoTenTextField.setValue('p');
                    	this.diaChiTextField.clearInvalid();
						this.diaChiTextField.setValue('p');
                    	this.dienThoaiTextField.setValue(null);
                    	this.dienThoaiTextField.clearInvalid();
                    	
                    	var oldMaHd = this.hdFieldSet.maHdTextField.getValue();
                    	var prexix = oldMaHd.substring(0, 3);
                    	var num = parseInt(oldMaHd.substring(3, oldMaHd.length)) + 1;
                    	this.hdFieldSet.maHdTextField.setValue(prexix + num);
                    	this.notifyMessage(result.msg);
                    	this.hoTenTextField.focus();
					}
				} else {
					this.notifyMessage(result.msg);
				}
            },
            failure : function(action, response) {
            	this.enableButtons();
            	if(response.response){
            		var result = Ext.decode(response.response.responseText);
            		this.hdFieldSet.maHdTextField.focus(true);
                	this.notifyMessage(result.msg);
            	}
            },
            scope : this
        });
	},
	
	save : function() {
		this.doSaveHopDong(this.isEdit ? 'hopDong/edit' : 'hopDong/save', false);
	},
	
	openSuaHdTraHang : function(){
		if (!this.traHangBtn.disabled) {
			Ext.Ajax.request({
	            url : 'hopDong/checkStatus',
	            params : { "id" : this.hdFieldSet.idHidden.getValue()},
	            method : 'GET',
	            scope : this,
	            success : function(response, opts){
	                var result = Ext.decode(response.responseText); 
	                if (result.isTraGop) {
	                	ApplicationManager.traHangFrom = MenuItemId.suaHD;
	                	ApplicationManager.openMenu(MenuItemId.suaHDTraHang);
					} else {
						Ext.Msg.alert(lang.text.ktraDlieu, lang.msg.onlyTraGopPass);
						return;
					}
	            }, 
	            failure : function() {
	            }
	        });
		}
    },

    openSuaHdDenHang : function(){
    	if (!this.denHangBtn.disabled) {
    		Ext.Ajax.request({
                url : 'hopDong/checkStatus',
                params : { "id" : this.hdFieldSet.idHidden.getValue()},
                method : 'GET',
                scope : this,
                success : function(response, opts){
                    var result = Ext.decode(response.responseText); 
                    if (result.isTraGop) {
                    	ApplicationManager.denHangFrom = MenuItemId.suaHD;
                    	ApplicationManager.openMenu(MenuItemId.suaHDDenHang);
    				} else {
    					Ext.Msg.alert(lang.text.ktraDlieu, lang.msg.onlyTraGopPass);
    					return;
    				}
                }, 
                failure : function() {
                }
            });
		}
    },
	
	inPhieuThu : function() {
		
	},
	
	exportPhieuThu : function(hopDongId) {
		var params = {'id' : hopDongId};
        var url = this.exportUrl+ "?"+ Ext.urlEncode(params);
        Utility.processExportWaiting(url);
	},
	
	loadMoreData : function(responseData) {
		this.hoTenTextField.setValue(responseData["khachHang-hoTen"]);
		this.diaChiTextField.setValue(responseData["khachHang-diaChi"]);
		this.dienThoaiTextField.setValue(responseData["khachHang-dienThoai"]);
		if (responseData["trangThaiText"] == lang.text.hd.tienMat) {
			this.hdFieldSet.thuTienNgayChkbox.setValue(true);
		}
		this.selectValueFromName(this.hdFieldSet.doiTruongCombo, responseData["nvDoiTruong-maNv"], true);
		this.selectValueFromName(this.hdFieldSet.nvBan1Combo, responseData["nvBan1-maNv"], true);
		this.selectValueFromName(this.hdFieldSet.nvBan2Combo, responseData["nvBan2-maNv"], true);
		this.selectValueFromName(this.hdFieldSet.thuNganCombo, responseData["nvThuNgan-maNv"], true);
		
		
		this.quanHuyenCombo.store.loadData(responseData["quanHuyen"]);
		this.phuongXaCombo.store.loadData(responseData["phuongXa"]);
		this.selectValueFromName(this.tinhThanhCombo, responseData["khachHang-tinhThanh"], false);
		this.selectValueFromName(this.quanHuyenCombo, responseData["khachHang-quanHuyen"], false);
		this.selectValueFromName(this.phuongXaCombo, responseData["khachHang-phuongXa"], false);
	},
	
	selectValueFromName : function(combo, name, isNv) {
		var idx = combo.store.findExact(isNv ? "maNv" : "giaTri", name);
		var record = combo.store.getAt(idx);
		if (record) {
			combo.setValue(record.get(isNv ? "id" : "maDuLieu"));
		}
	},
	
	beforeRequestHdInfo : function() {
		this.resetValue();
		this.disableComponents();
	},
	
	afterRequestHdInfo : function() {
		this.hoTenTextField.enable();
		this.diaChiTextField.enable();
		this.dienThoaiTextField .enable();
		this.tinhThanhCombo.enable();
		this.quanHuyenCombo.enable();
		this.phuongXaCombo.enable();
		this.hdFieldSet.doiTruongCombo.enable();
		this.hdFieldSet.nvBan1Combo.enable();
		this.hdFieldSet.nvBan2Combo.enable();
		this.hdFieldSet.thuNganCombo.enable();
		this.hdFieldSet.ngayBanDateField.enable();
		this.hdFieldSet.dotBanTextField.enable();
		this.hdFieldSet.giaTriTextField.enable();
		this.hdFieldSet.tienTraTruocTextField.enable();
		this.hdFieldSet.tienDaThuTextField.enable();
		this.hdFieldSet.giaTriTextField.setReadOnly(true);
		this.hdFieldSet.dotBanTextField.setReadOnly(true);
		this.hdFieldSet.tienTraTruocTextField.setReadOnly(true);
		this.hdFieldSet.tienDaThuTextField.setReadOnly(true);
		this.luuBtn.enable();
		this.inBtn.enable();
		if (ApplicationManager.hdInfo.thuNgan != "" && ApplicationManager.hdInfo.thuNgan != null && 
				ApplicationManager.hdInfo.daGiaoPhieu != "true") {
			this.denHangBtn.enable();
			this.traHangBtn.enable();
		}
	},
	
	disableComponents : function() {
		this.hoTenTextField.disable();
		this.diaChiTextField.disable();
		this.dienThoaiTextField .disable();
		this.tinhThanhCombo.disable();
		this.quanHuyenCombo.disable();
		this.phuongXaCombo.disable();
		this.hdFieldSet.doiTruongCombo.disable();
		this.hdFieldSet.nvBan1Combo.disable();
		this.hdFieldSet.nvBan2Combo.disable();
		this.hdFieldSet.thuNganCombo.disable();
		this.hdFieldSet.ngayBanDateField.disable();
		this.hdFieldSet.dotBanTextField.disable();
		this.hdFieldSet.giaTriTextField.disable();
		this.hdFieldSet.tienTraTruocTextField.disable();
		this.hdFieldSet.tienDaThuTextField.disable();
		this.luuBtn.disable();
		this.inBtn.disable();
		this.denHangBtn.disable();
		this.traHangBtn.disable();
	},
	
	resetValue : function() {
		this.hoTenTextField.reset();
		this.diaChiTextField.reset();
		this.dienThoaiTextField.reset();
		this.tinhThanhCombo.clearValue(null);
		this.quanHuyenCombo.clearValue(null);
		this.phuongXaCombo.clearValue(null);
		this.hdFieldSet.doiTruongCombo.clearValue(null);
		this.hdFieldSet.nvBan1Combo.clearValue(null);
		this.hdFieldSet.nvBan2Combo.clearValue(null);
		this.hdFieldSet.thuNganCombo.clearValue(null);
		this.hdFieldSet.ngayBanDateField.reset();
		this.hdFieldSet.thuTienNgayChkbox.reset();
		this.hdFieldSet.dotBanTextField.reset();
		this.hdFieldSet.giaTriTextField.reset();
		this.hdFieldSet.tienTraTruocTextField.reset();
		this.hdFieldSet.tienDaThuTextField.reset();
		this.hdFieldSet.tienConLaiTextField.reset();
		this.hdFieldSet.idHidden.setValue(null);
	}
});